package cn.rs.lvt.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.nio.charset.Charset;
import java.util.Objects;
import java.util.Optional;

/**
 * 应用启动后打印应用信息
 *
 * @author 吕晓飞
 * @version 1.0
 * @since 2024/8/16 11:06
 */
@Component
public class AppInfoPrinter implements CommandLineRunner {

    @Autowired
    private Environment env;

    @Override
    public void run(String... args) throws Exception {
        String contextPath = env.getProperty("server.servlet.context-path", "");
        String protocol = Optional.ofNullable(env.getProperty("server.ssl.key-store")).map(key -> "https").orElse("http");
        String port = env.getProperty("server.port", "");
        String dbConnect = env.resolveRequiredPlaceholders(Objects.requireNonNull(env.getProperty("spring.datasource.url", "")));

        System.out.println("---------------------------------------------------------------");
        System.out.printf("%15s: %s\r\n", "AppName", env.getProperty("spring.application.name", ""));
        System.out.printf("%15s: %s\r\n", "Profiles", String.join(",", env.getActiveProfiles()));
        System.out.printf("%15s: %s://localhost:%s%s\r\n", "LocalAddr", protocol, port, contextPath);
        System.out.printf("%15s: %s://%s:%s%s\r\n", "External", protocol, getLocalIp(), port, contextPath);
        System.out.printf("%15s: %s://%s:%s%s/swagger-ui.html\r\n", "OpenApi", protocol, getLocalIp(), port, contextPath);
        System.out.printf("%15s: %s://%s:%s%s/doc.html\r\n", "Knife4j", protocol, getLocalIp(), port, contextPath);
        System.out.printf("%15s: %s\r\n", "DBUrl", dbConnect);
        System.out.printf("%15s: %s\r\n", "file.encoding", Charset.defaultCharset().displayName());
        System.out.println("---------------------------------------------------------------");
    }

    /**
     * 获取本机 IP
     */
    private static String getLocalIp() {
        try {
            return InetAddress.getLocalHost().getHostAddress();
        } catch (Exception e) {
            return "127.0.0.1";
        }
    }


}
